# -*- coding: UTF-8 -*-
import os
import time

import re
import threading
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotVisibleException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pyquery import PyQuery as pq
from datetime import datetime, timedelta

from subprocess import call

from dash_lib.mongodb_helper import bulk_insert, bulk_insert_feed


def not_empty(s):
    return s and s.strip()


def loadNext():
    driver.find_element_by_xpath("//a[contains(text(),'See older')]").click()
    time.sleep(1)


def is_not_finished(last_pick):
    # if is_hot_update and (count > 4):
    #     return False
    # else:
    if last_pick and is_reach_last_fetch_page(last_pick):
        return False
    else:
        try:
            WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, "//a[contains(text(),'See older')]")))
            return True
        except TimeoutException:
            return False


def is_reach_last_fetch_page(last_pick):
    print('last_pick', last_pick)
    resultList = handle_feed_list()

    result = list(filter(lambda
                             x: x[0] == last_pick['match'] and x[1] == last_pick['pick'] and x[3] == last_pick[
        'stake'] and x[10] == last_pick['kickoff_time']
                         , resultList))
    # if result:
    #     print('result', result, len(result))
    # else:
    #     print('found no last pick')

    return True if result else False


def get_last_updat_time(parent_view):
    find = parent_view.find('.title-name').find('.col-sm-5.col-lg-6.title-age')
    find_find = find.find('.bet-age.text-muted')
    now = datetime.now()
    last_update_str = find_find.text().replace('st', "").replace('nd', "").replace('rd', "").replace('th', "")
    if 'secs ago' in last_update_str:
        _delta = int(last_update_str.replace('secs ago', ''))
        _datetime = now - timedelta(seconds=_delta)
    elif 'mins ago' in last_update_str or 'min ago' in last_update_str:
        _delta = int(last_update_str.replace('mins ago', '').replace('min ago', ''))
        _datetime = now - timedelta(minutes=_delta)
    elif 'hrs ago' in last_update_str or 'hr ago' in last_update_str:
        _delta = int(last_update_str.replace('hrs ago', '').replace('hr ago', ''))
        _datetime = now - timedelta(hours=_delta)
    else:
        _datetime = datetime.strptime(last_update_str, '%a, %b %d, %Y, %H:%M')
    return _datetime


def handle_feed_list():
    html = driver.page_source
    resultList = []
    if html:
        doc = pq(html)
        _last_kickoff_date = None
        items = doc('.media-body')
        for item in items.items():
            if not not_empty(item.text()):
                continue
            try:
                last_updat_time = get_last_updat_time(item)
                tipper = item.find('.title-name').find('.col-sm-7.col-lg-6.no-padding').find('.font-bold').attr(
                    'href').lower().replace(".blogabet.com", '').replace("https://", '')
                last_update = last_updat_time.strftime('%Y-%m-%d %H:%M')
                item_view = item.find('.feed-pick-title').find('.col-xs-12.no-padding')
                plain_item_view_txt = re.sub(r'\r\n|\n|\r/gm', ";", item_view.text())
                if item_view.find('h3').find('.combo-toggle') or plain_item_view_txt.find(
                        'Combo') != -1:
                    pick_type = 'Combo'
                    match = 'Combo'
                    sport = 'Combo'
                    category = ''
                    if not _last_kickoff_date:
                        _last_kickoff_date = last_updat_time
                else:
                    match = item_view.find('h3').find('a').text()
                    if not match:
                        match = list(filter(not_empty, plain_item_view_txt.split(';')))[0]
                    pick_type = 'LIVE' if item_view.find('.labels').find('.label.label-danger') else 'Single'
                    sport_line = re.sub(r'\r\n|\n|\r/gm', "",
                                        item_view.find('.sport-line').text().replace('Kick off:', ''))
                    sport_line_splits = sport_line.split('/')
                    sport = sport_line_splits[0]
                    category = sport_line_splits[1]
                    _last_kickoff_date = datetime.strptime(not_empty(sport_line_splits[2]), '%d %b %Y, %H:%M')

                kickoff = _last_kickoff_date.strftime('%Y-%m-%d')
                kickoff_time = _last_kickoff_date.strftime('%H:%M')
                pick_txt = item_view.find('.pick-line').text()
                pick = pick_txt.split('@')[0]
                odd = float(pick_txt.split('@')[1])
                stake = int(item_view.find('.labels').find('.label.label-default').text().replace('/10', ''))
                win = item_view.find('.labels').find('.enable-tooltip.text-green')
                lost = item_view.find('.labels').find('.enable-tooltip.text-danger')
                book_maker = item_view.find('.labels').find('.label.label-primary').text()

                if not win and not lost:
                    result = 'PENDING'
                    profit = None
                else:
                    try:
                        profit = float(win.text() if win else lost.text())
                    except ValueError:
                        profit = 0
                    result = win.attr('data-original-title') if win else lost.attr('data-original-title')

                resultList.append((not_empty(tipper),
                                   not_empty(match), not_empty(pick), odd, stake, pick_type, profit,
                                   not_empty(result), not_empty(sport), not_empty(category), not_empty(kickoff),
                                   kickoff_time,
                                   last_update, book_maker))

            except (IndexError, ValueError) as e:
                print(str(e))
    else:
        print(u'抓取网页失败，跳过')
    return resultList


def refresh():
    if EC.visibility_of_element_located((By.XPATH, '//ul[@id="feed-list"]')):
        driver.find_element_by_xpath('//a[@id="reloadFeedBtn"]').click()
    WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, '//ul[@id="feed-list"]')))

    feed_list = handle_feed_list()
    bulk_insert_feed(feed_list)


def loop_refresh():
    print('loop_refresh', datetime.now())
    refresh()
    global timer
    timer = threading.Timer(45, loop_refresh)
    timer.start()


def start():
    print('start_loop', datetime.now().strftime('%d %b, %H:%M'))
    timer = threading.Timer(3, loop_refresh)
    timer.start()


def login():
    driver.get('https://blogabet.com')
    try:
        driver.find_element_by_xpath('//button[@id="impliedsubmit"]').click()
    except (NoSuchElementException, ElementNotVisibleException):
        pass

    time.sleep(1)
    WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, '//a[@class="btn btn-outline"]')))
    driver.find_element_by_xpath('//a[@class="btn btn-outline"]').click()
    WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, '//div[@class="modal-backdrop fade in"]')))
    # time.sleep(2)
    # driver.find_element_by_xpath('//button[@type="submit"]')
    WebDriverWait(driver, 15).until(
        EC.visibility_of_element_located((By.XPATH, '//input[@id="email"][@placeholder="Email"]')))

    email = driver.find_element_by_xpath('//input[@id="email"][@placeholder="Email"]')
    password = driver.find_element_by_xpath('//input[@id="password"][@placeholder="Password"]')

    email.send_keys('feiyahui000@gmail.com')
    password.send_keys('Freddy666')
    driver.find_element_by_xpath('//button[@type="submit"]').click()

    WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, '//a[@data-tab="mytipsters"][@id="mytipsters_feed"]')))
    driver.find_element_by_xpath('//a[@id="mytipsters_feed"]').click()


driver = webdriver.Chrome()
login()
start()
